﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace hoemwork
{

    /*让之前的双向链表，能够：被foreach迭代*/
    public class DLink : IEnumerable
    {
        public static void DLinkForeach()
        {
            DLink node1 = new DLink { Value = 1 };
            DLink node2 = new DLink { Value = 2 };
            DLink node3 = new DLink { Value = 3 };
            DLink node4 = new DLink { Value = 4 };
            node1.AddAfter(node2);
            node2.AddAfter(node3);
            node3.AddAfter(node4);
            foreach (var item in node1)
            {
                Console.WriteLine(item);
            }
        }

        public int Value { get; set; }
        public DLink Previous { get; set; }
        public DLink Next { get; set; }
        public void AddAfter(DLink node)
        {
            if (this.Next != null)
            {
                node.Next = this.Next;
                this.Next.Previous = node;
            }
            this.Next = node;
            node.Previous = this;
        }
        public void AddBefore(DLink node)
        {

            if (this.Previous == null)
            {
                this.Previous = node;
                node.Next = this;

            }
            else
            {
                this.Previous.AddAfter(node);
            }





        }
        public static void Delete(DLink node)
        {
            if (node.Previous == null)
            {
                node.Next.Previous = null;

            }
            else if (node.Next == null)
            {
                node.Previous.Next = null;

            }
            else
            {
                node.Previous.Next = node.Next;
                node.Next.Previous = node.Previous;
            }
            node.Previous = null;
            node.Next = null;
        }

        public IEnumerator GetEnumerator()//调用方法得到实例
        {
            return new Enumerator(this);
        }

        public struct Enumerator : IEnumerator
        {
            private DLink _current;//当前元素
            private bool firstnode;
            public object Current => _current;
            public Enumerator(DLink node)//构造函数赋值
            {
                _current = node; //当前元素
                firstnode = true;
            }
            public bool MoveNext()//循环输出输出节点
            {                       //节点值往后走
                if (firstnode)
                {
                    firstnode = false;
                    return true;
                }
                if (_current.Next == null)//节点等于null终止
                {
                    return false;
                }

                _current = _current.Next;

                return true;
            }

            public void Reset()
            {
                throw new NotImplementedException();
            }
        }

    }
}

























